package com.baizhi.controller;

import com.baizhi.entity.Poetries;
import com.baizhi.util.ESUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("poetries")
public class PoetriesController {

    //从ES中查询展示到页面
    @RequestMapping("show")
    public Map show(String content, Integer page, Integer limit){
        //创建client连接
        TransportClient client = ESUtils.getClient();
        //判断concent关键字是否为空  条件查询还是全部查询
        QueryBuilder builder = null;
        if(content!=null && content.trim().length()>0){
            builder = QueryBuilders.termQuery("content",content);
        }else {
            builder = QueryBuilders.matchAllQuery();
        }
        //高亮查询准备
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("content");//以es中的content字段作为高亮查询的字段
        //执行查询操作
        SearchResponse searchResponse = client.prepareSearch("es4").setTypes("poetries")
                .setQuery(builder)
                .setFrom((page-1)*limit)
                .setSize(limit)
                .highlighter(highlightBuilder)
                .addSort("id", SortOrder.ASC)
                .get();
        //获取查询ES后的结果中的数据
        SearchHits hits = searchResponse.getHits();
        long totalHits = hits.getTotalHits();//查询结果数据的总条数
        List list = new ArrayList<>();//定义一个list集合用于保存展示到页面的数据
        for (SearchHit hit : hits) {
            //遍历查询ES中的结果  将每一条数据封装到poetries对象中 再添加到list集合中
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //若是关键字content查询  则会执行高亮操作 要把上面sourceAsMap中的content字段值替换为高亮后的数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField content1 = highlightFields.get("content");
            if(content1!=null){
                String s = content1.fragments()[0].toString();
                sourceAsMap.put("content",s);
            }
            list.add(sourceAsMap);
        }
        //设置响应页面数据
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","");
        map.put("count",totalHits);
        map.put("data",list);
        return map;
    }

}
